/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.sciPersonnelInfo.service;

import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.requirement.domain.Requirement;
import com.fzhucc.modules.requirement.domain.RequirementMsgBox;
import com.fzhucc.modules.requirement.domain.dto.RequirementBoxSeekDto;
import com.fzhucc.modules.requirement.domain.dto.RequirementMsgBoxDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfo;
import com.fzhucc.modules.sciPersonnelInfo.domain.SciPersonnelInfoMsgBox;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoBoxSeekDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoQueryCriteria;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoRepository;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMapper;
import com.fzhucc.modules.sciTechnologyDemand.domain.SciTechnologyDemand;
import com.fzhucc.modules.sciTechnologyDemand.domain.dto.SciTechnologyDemandMsgBoxDto;
import com.fzhucc.modules.sciTechnologyDemand.repository.SciTechnologyDemandRepository;
import com.fzhucc.modules.sciTechnologyDemand.service.mapstruct.SciTechnologyDemandMapper;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import com.fzhucc.modules.sciPersonnelInfo.repository.SciPersonnelInfoMsgBoxRepository;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoMsgBoxDto;
import com.fzhucc.modules.sciPersonnelInfo.domain.dto.SciPersonnelInfoMsgBoxQueryCriteria;
import com.fzhucc.modules.sciPersonnelInfo.service.mapstruct.SciPersonnelInfoMsgBoxMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2023-12-14
 **/
@Service
@RequiredArgsConstructor
public class SciPersonnelInfoMsgBoxService {

    @Value("${org.area.all}")
    public String all;

    private final SciPersonnelInfoMsgBoxRepository sciPersonnelInfoMsgBoxRepository;

    private final SciPersonnelInfoRepository sciPersonnelInfoRepository;

    private final SciTechnologyDemandRepository sciTechnologyDemandRepository;
    private final SciPersonnelInfoMsgBoxMapper sciPersonnelInfoMsgBoxMapper;

    private final SciPersonnelInfoMapper sciPersonnelInfoMapper;

    private final SciTechnologyDemandMapper sciTechnologyDemandMapper;

    private final UserRepository userRepository;

    public Map<String, Object> queryAll(SciPersonnelInfoMsgBoxQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<SciPersonnelInfoMsgBox> page = sciPersonnelInfoMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<SciPersonnelInfoMsgBoxDto> map = page.map(sciPersonnelInfoMsgBoxMapper::toDto);
        List<SciPersonnelInfoMsgBoxDto> lists = map.getContent();
        if (lists != null && lists.size() > 0) {
            for (SciPersonnelInfoMsgBoxDto sciPersonnelInfoMsgBoxDto : lists) {
                Integer spId = sciPersonnelInfoMsgBoxDto.getSpId();
                if (spId != null) {
                    Optional<SciPersonnelInfo> result = sciPersonnelInfoRepository.findById(spId);
                    sciPersonnelInfoMsgBoxDto.setSciPersonnelInfoDto(sciPersonnelInfoMapper.toDto(result.get()));
                }

                Integer tdId = sciPersonnelInfoMsgBoxDto.getTdId();
                if (tdId != null) {
                    Optional<SciTechnologyDemand> result2 = sciTechnologyDemandRepository.findById(tdId);
                    sciPersonnelInfoMsgBoxDto.setSciTechnologyDemandDto(sciTechnologyDemandMapper.toDto(result2.get()));
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看
    public String setCriteria(SciPersonnelInfoMsgBoxQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            //throw new RuntimeException(e);
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && res.getOrgArea().equals(all)) {//用的org组织最高看全部
                return null;
            } else {
                return res.getOrgArea();//如果用户的权限不是福建省则 只能看到对应的组织
            }
        } else {
            return null;
        }
    }

    public List<SciPersonnelInfoMsgBoxDto> queryAll(SciPersonnelInfoMsgBoxQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return sciPersonnelInfoMsgBoxMapper.toDto(sciPersonnelInfoMsgBoxRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Transactional
    public SciPersonnelInfoMsgBoxDto findById(Integer id) {
        SciPersonnelInfoMsgBox sciPersonnelInfoMsgBox = sciPersonnelInfoMsgBoxRepository.findById(id).orElseGet(SciPersonnelInfoMsgBox::new);
        ValidationUtil.isNull(sciPersonnelInfoMsgBox.getId(), "SciPersonnelInfoMsgBox", "id", id);
        return sciPersonnelInfoMsgBoxMapper.toDto(sciPersonnelInfoMsgBox);
    }

    @Transactional(rollbackFor = Exception.class)
    public SciPersonnelInfoMsgBoxDto create(SciPersonnelInfoMsgBox resources) {
        return sciPersonnelInfoMsgBoxMapper.toDto(sciPersonnelInfoMsgBoxRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(SciPersonnelInfoMsgBox resources) {
        SciPersonnelInfoMsgBox sciPersonnelInfoMsgBox = sciPersonnelInfoMsgBoxRepository.findById(resources.getId()).orElseGet(SciPersonnelInfoMsgBox::new);
        ValidationUtil.isNull(sciPersonnelInfoMsgBox.getId(), "SciPersonnelInfoMsgBox", "id", resources.getId());
        sciPersonnelInfoMsgBox.copy(resources);
        sciPersonnelInfoMsgBoxRepository.save(sciPersonnelInfoMsgBox);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            sciPersonnelInfoMsgBoxRepository.deleteById(id);
        }
    }

    public void download(List<SciPersonnelInfoMsgBoxDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SciPersonnelInfoMsgBoxDto sciPersonnelInfoMsgBox : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("助企行劳模id", sciPersonnelInfoMsgBox.getSpId());
            map.put("咨询内容", sciPersonnelInfoMsgBox.getContent());
            map.put("联系方式", sciPersonnelInfoMsgBox.getPhone());
            map.put("咨询时间", sciPersonnelInfoMsgBox.getConsultationTime());
            map.put("咨询人姓名", sciPersonnelInfoMsgBox.getName());
            map.put("单位", sciPersonnelInfoMsgBox.getUnit());
            map.put("地区组织机构区分  与劳模工匠对应的一致", sciPersonnelInfoMsgBox.getOrgArea());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Transactional(rollbackFor = Exception.class)
    public SciPersonnelInfoMsgBoxDto seek(SciPersonnelInfoBoxSeekDto dto) {
        SciPersonnelInfoMsgBox sciPersonnelInfoMsgBox = new SciPersonnelInfoMsgBox();
        Optional<SciPersonnelInfo> res = sciPersonnelInfoRepository.findById(dto.getSciPersonnelInfoId());
        if (!res.isPresent()) {
            throw new BadRequestException("未找到该劳模工匠");
        }
        sciPersonnelInfoMsgBox.setSpId(dto.getSciPersonnelInfoId());
        if (dto.getSciTechnologyDemandId() == null) {
            sciPersonnelInfoMsgBox.setTdId(null);
        } else {
            Optional<SciTechnologyDemand> res2 = sciTechnologyDemandRepository.findById(dto.getSciTechnologyDemandId());
            if (!res2.isPresent()) {
                throw new BadRequestException("未找到该需求");
            }
            sciPersonnelInfoMsgBox.setTdId(dto.getSciTechnologyDemandId());
        }
        sciPersonnelInfoMsgBox.setPhone(dto.getPhone());
        sciPersonnelInfoMsgBox.setConsultationTime(new Timestamp(new Date().getTime()));
        sciPersonnelInfoMsgBox.setContent(dto.getContent());
        sciPersonnelInfoMsgBox.setName(dto.getName());
        sciPersonnelInfoMsgBox.setUnit(dto.getUnit());
        sciPersonnelInfoMsgBox.setOrgArea(res.get().getOrgArea());//劳模的org
        SciPersonnelInfoMsgBox save = sciPersonnelInfoMsgBoxRepository.save(sciPersonnelInfoMsgBox);
        //TODO 留言热度+10
        SciPersonnelInfo sciPersonnelInfo = res.get();
        Integer hot = sciPersonnelInfo.getHot();
        sciPersonnelInfo.setHot(hot + 10);
        sciPersonnelInfoRepository.save(sciPersonnelInfo);
        return sciPersonnelInfoMsgBoxMapper.toDto(save);
    }
}